/*
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)
*/

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<vector<int> > ret;
        if(num.size() < 4) return ret;
        sort(num.begin(), num.end());
        for(int i = 0; i < num.size(); ++i) {
            for(int j = i + 1; j < num.size(); ++j) {
                int left = j + 1;
                int right = (int)num.size() - 1;
                while(left < right) {
                    int sum = num[i]+num[j]+num[left]+num[right]; 
                    if(target == sum) {
                        vector<int> resone;
                        resone.push_back(num[i]);
                        resone.push_back(num[j]);
                        resone.push_back(num[left]);
                        resone.push_back(num[right]);
                        ret.push_back(resone);
                        ++left; --right; 
                    } else if (sum > target) --right;
                    else ++left;
                }
            }
        }
        sort(ret.begin(), ret.end()); 
        ret.resize(unique(ret.begin(),ret.end())-ret.begin());
        return ret;        
    }
};
